using UnityEngine;
using System.Collections;
using UnityEditor;

[CustomEditor(typeof(C2DSpline))]
public class C2DSplineEditor : Editor 
{
	enum SplineEditorMode
	{
		Disabled = 0,
		Edit,
		Select
	}
	
	SplineEditorMode m_Mode = SplineEditorMode.Disabled;
	
	C2DControlPoint m_currentPoint = null;

	public override void OnInspectorGUI()
	{
		m_Mode = (SplineEditorMode)EditorGUILayout.EnumPopup( m_Mode );
		
		DrawDefaultInspector();
	}
	
	public void OnSceneGUI()
	{	
		C2DSpline spline =(C2DSpline)(target);
		
		if( spline != null )
		{	
			Ray worldRay = HandleUtility.GUIPointToWorldRay (Event.current.mousePosition);
		    RaycastHit hitInfo;
			bool bSelect = Physics.Raycast(worldRay, out hitInfo);
			
			if( m_Mode != SplineEditorMode.Disabled )
			{
				switch( Event.current.type )
				{
					case EventType.mouseDown:
	        			if( Event.current.button == 0 )
	        			{
							if( m_Mode == SplineEditorMode.Edit )
							{	
		          				if( bSelect )
					        	{
									if( m_Mode == SplineEditorMode.Edit )
									{
			            				Undo.RegisterUndo(target, "Add Spline Node");
										spline.AddNode( hitInfo.point );
										Event.current.Use();
									}
								}
							}
							else if( m_Mode == SplineEditorMode.Select )
							{
								if (Physics.Raycast(worldRay, out hitInfo))
								{
									Undo.RegisterUndo(target, "Select Spline Node");
									m_currentPoint = spline.SelectPoint( hitInfo.point );
									Event.current.Use();
								}
							}
						}
					break;
					
					case EventType.keyDown:
					{
						if( Event.current.keyCode == KeyCode.Delete && m_currentPoint != null )
						{
							Undo.RegisterUndo(target, "Delete Spline Node");
							spline.m_ControlPoints.RemoveAt( spline.m_ControlPoints.IndexOf( m_currentPoint ) );
							m_currentPoint = null;
							Event.current.Use();
						}
					}
					break;
					
					case EventType.mouseDrag:
						if( Event.current.button == 0 && m_Mode == SplineEditorMode.Select && m_currentPoint != null && bSelect )
						{
							Vector3 pos = m_currentPoint.m_Position;
							pos.x = hitInfo.point.x;
							pos.y = hitInfo.point.y;
					
							m_currentPoint.m_Position = pos;
							Event.current.Use();
						}
					break;
					
					case EventType.layout:
						HandleUtility.AddDefaultControl(GUIUtility.GetControlID(GetHashCode(), FocusType.Passive));
					break;
				}
	
				for( int n=0; n < spline.m_ControlPoints.Count; n++ )
				{
					if( n > 0 )
					{
						Handles.DrawLine( spline.m_ControlPoints[n-1].m_Position, spline.m_ControlPoints[n].m_Position );
					}
					
					Handles.DrawSolidDisc( spline.m_ControlPoints[n].m_Position, Vector3.forward, C2DSpline.CONTROL_POINT_SIZE ); 
				}
			}
		}
	}
}
